import axios from 'axios'
import { ElMessage } from 'element-plus'

// Create axios instance
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Request interceptor
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// Response interceptor
api.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error('没有权限访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(error.response.data.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    return Promise.reject(error)
  }
)

// API functions
export const login = (data) => {
  return api.post('/auth/login', data)
}

export const getUserInfo = () => {
  return api.get('/auth/userinfo')
}

// User management APIs
export const getAllUsers = () => {
  return api.get('/api/users')
}

export const getUserList = (params) => {
  return api.get('/api/users', { params })
}

export const getUserById = (id) => {
  return api.get(`/api/users/${id}`)
}

export const createUser = (data) => {
  return api.post('/api/users', data)
}

export const updateUser = (id, data) => {
  return api.put(`/api/users/${id}`, data)
}

export const deleteUser = (id) => {
  return api.delete(`/api/users/${id}`)
}

// Dictionary management APIs
export const getDictionaryList = (params) => {
  return api.get('/dictionary', { params })
}

export const getDictionaryById = (id) => {
  return api.get(`/dictionary/${id}`)
}

export const getDictionaryByType = (dictType) => {
  return api.get(`/dictionary/type/${dictType}`)
}

export const createDictionary = (data) => {
  return api.post('/dictionary', data)
}

export const updateDictionary = (id, data) => {
  return api.put(`/dictionary/${id}`, data)
}

export const deleteDictionary = (id) => {
  return api.delete(`/dictionary/${id}`)
}

export default api